define(["jquery","bbcare","as/app/dst/dstDetail.servers","as/app/dst/dstDetail.ui"],function($,$bb,$servers,$ui){
	var event = {};
	var resultArr = []; // 答案
	var w_diff, w_li, status;

	/**
	 * 评估提交成功后的回调函数
	 */
	var ajaxSubmitGetScoreCallBack = function(data){
		$bb.toastShow("提交成功！");
		// $(".dstDetail-wrap").parents(".assess-wrap").length 判断是从患者中心打开 还是从dst菜单打开
		if( $(".dstDetail-wrap").parents(".assess-wrap").length == 0 ){
			$bb.openPage("dstHistoryRecord",data);
		}else{
			$.get("page/assess/html/dst/dstHistoryRecord.html",function(html){
				$(".assess-wrap").html(html);
			});
		}
	}

	/**
	 * 获取、处理答案
	 */
	var getAnswer = function(type){
		var obj = {};
		var arr = $("#dstDetailType > div.item.dstDetail-af-" + type).data("answer");
		if( arr && arr.length > 0 ){
			for (var i = 0; i < arr.length; i++) {
				for(var j = 0; j < arr[i].question.length; j++ ){
					obj[arr[i].question[j].id] = Number(arr[i].question[j].result);
				}
			}
		}
		return obj;
	}

	/**
	 * 所有答案的集合  为了返回的渲染
	 */
	var getGatherAnswer = function(type){
		var obj = {};
		var arr1 = $("#dstDetailType > div.item.dstDetail-af-intelligence").data("answer");
		var arr2 = $("#dstDetailType > div.item.dstDetail-af-sociology").data("answer");
		var arr3 = $("#dstDetailType > div.item.dstDetail-af-sports").data("answer");
		obj.intelligence = arr1;
		obj.sociology = arr2;
		obj.sports = arr3;
		return obj;
	}

	/**
	 * 计算出各个能区计算出的分数
	 */
	var getScore = function(type,obj){
		var questions = $("#dstDetailType .item.dstDetail-af-" + type).data("questions");
		var top = $("#topicTop").data(type);
		var topQuestId; // 顶点问题id
		if( top ){
			for (var i = 0; i < questions.length; i++) {
				if( questions[i].id == Number(top.monthId) ){
					topQuestId = questions[i].question[0].id;
					break;
				}
			}
		}
		var score = 0;
		var num = 0; // 顶点之前的题目被做的个数
		for(var key in obj){
			score += obj[key];
			if( key < topQuestId ){
				num++;
			}
		}
		if( topQuestId ) score = score + ( topQuestId - 1 ) - num;
		return score;
	}

	/**
	 * 获取各个能区的顶点和底点
	 */
	var getPoint = function($dom){
		var data = $dom.data();
		return {
			"intelligence":data.intelligence,
			"sociology":data.sociology,
			"sports":data.sports,
		};
	}

	/**
	 * 集合答案
	 */
	var getAllAnswer = function(){
		var answer = {};
		answer.gather = getGatherAnswer(); // 为了保存之后再点击返回的渲染
		answer.intelligence = getAnswer("intelligence");
		answer.sociology = getAnswer("sociology");
		answer.sports = getAnswer("sports");
		answer.intelligenceScore = getScore("intelligence",answer.intelligence);
		answer.sociologyScore = getScore("sociology",answer.sociology);
		answer.sportsScore = getScore("sports",answer.sports);
		answer.top = getPoint( $("#topicTop") );
		answer.bottom = getPoint( $("#topicBottom") );
		return answer;
	}

	/**
	 * 全部结束
	 */
	var onAllEnd = function(){
		var data = $(this).data("data");
		$("."+data.className).modal("hide");
		emptyTopAndBottom(data.type,"topicTop",true);
		emptyTopAndBottom(data.type,"topicBottom",true);
		$("#dstDetailType > div.item.active").data("answer",resultArr);
		$("#dstDetailType > div.item.active").addClass("actived");
		// 提交
		var channelId = $bb.getChannelId();
		var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
		var info = $("#dstDetailLook").data("info");
		var postionIds = JSON.stringify(getAllAnswer());
		var params = {
			"oprInfo":{
				"opCode":"1124",
				"opType":"0",
				"opNote":"【"+ doctorName +"】医生为【"+ info.userName +"】患者上传DST评估数据",
				"channelType":"2",
				"channelId":channelId,
			},
			"evaluationType":"DST",
			"queueUserId":info.userId,
			"postionIds":postionIds,
		};
		if( $(".dstDetail-wrap").parents(".assess-wrap").length > 0 ){
			var taskId = $(".dstDetail-wrap").parents(".assess-wrap").data("ptTaskId");
			$.extend(params,{"taskId":taskId});
		}
		$servers.ajaxSubmitGetScore(params,ajaxSubmitGetScoreCallBack);
	}

	/**
	 * 清空顶部、底部里展示的月份，并将月份和月份id转存在对应的data-能区里
	 */
	var emptyTopAndBottom = function(type,domId,flag){
		var obj = {
			"monthName":$("#"+domId).html(),
			"monthId":$("#"+domId).attr("data-monthId"),
		}
		$("#"+domId).data(type,obj);
		if( !flag ){
			$("#"+domId).html("不确定");
			$("#"+domId).removeAttr("data-monthId");
		}
	}

	/**
	 * 进入下一能区
	 */
	var onGoNextType = function(){
		var data = $(this).data("data");
		$("."+data.className).modal("hide");
		emptyTopAndBottom(data.type,"topicTop");
		emptyTopAndBottom(data.type,"topicBottom");
		$("#dstDetailType > div.item.active").data("answer",resultArr);
		var nextIndex = $("#dstDetailType > div.item.active").index() + 1;
		$("#dstDetailType > div.item.active").addClass("actived").removeClass("active");
		$("#dstDetailType .item").eq(nextIndex).click();
	}

	/**
	 * 修改上一题
	 */
	var onEditPrev = function(){
		var data = $(this).data("data");
		$("."+data.className).modal("hide");
		$("#dstDetailQuest .quest-resut > div").unbind("click");
		$("#dstDetailQuest .quest-resut > div").data("data",{"questions":data.questions});
		$("#dstDetailQuest .quest-resut > div").click(onDoQuest);
	}

	/**
	 * 一个能区做完了的提示框
	 */
	var endMsg = function(className,questions){
		var type = $("#dstDetailType > div.item.active").attr("data-type");
		$ui.end({
        	"dom":$("." + className + " .modal-body"),
        	"data":$servers.handleTypeData(type),
        });
        $("."+className).modal("show");
        // 修改上一题
        $("#editPrev").unbind("click");
        $("#editPrev").data("data",{"questions":questions,"className":className});
        $("#editPrev").click(onEditPrev);
        // 进入下一能区
        $("#goNextType").unbind("click");
        $("#goNextType").data("data",{"className":className,"type":type});
        $("#goNextType").click(onGoNextType);
        // 全部结束
        $("#allEnd").unbind("click");
        $("#allEnd").data("data",{"className":className,"type":type});
        $("#allEnd").click(onAllEnd);
	}

	/**
	 * 结束模态框
	 */
	var endMsgModal = function(questions){
		var className = "endModal";
		$bb.modal({
			"id":"dstDetail",
            "className": className,
            "tit": "结束",
        },function(){
        	endMsg(className,questions);
        });
	}

	/**
	 * 找到0月还未找到顶点的提示语
	 */
	var tipMsg = function(className,locationObj){
		$ui.tip({
        	"dom":$("." + className + " .modal-body"),
        });
        $("."+className).modal("show");
        // 不继续做了
        $("#continueN").unbind("click");
        $("#continueN").click(function(){
        	$("."+className).modal("hide");
        });
        // 继续做题
        $("#continueY").unbind("click");
        $("#continueY").click(function(){
        	$("."+className).modal("hide");
        	$("#tabShow ul li").eq(locationObj.monthIndex).find("span").eq(locationObj.questIndex).click();
        });
	}

	/**
	 * 提示语模态框
	 */
	var tipMsgModal = function(locationObj){
		var className = "tipModal";
		$bb.modal({
			"id":"dstDetail",
            "className": className,
            "tit": "提示语",
        },function(){
        	tipMsg(className,locationObj);
        });
	}

	/**
	 * 做题目的时候，暂存答案以及tab样式变化
	 */
	var presentSave = function(monthId,id,result,index){
		var $monthDom = $("#tabShow ul li").eq(monthId-1).children(".tab-month");
		var $questDom = $("#tabShow ul li").eq(monthId-1).find(".tab-quest-box span").eq(index);
		$questDom.attr("data-answer",result);
		$monthDom.removeClass("active").addClass("actived");
		if( result == "1" ){
			$questDom.removeClass("active actived-fail").addClass("actived-success");
		}else if( result == "0" ){
			$questDom.removeClass("active active-success").addClass("actived-fail");
		}
		resultArr = $servers.getResult(resultArr,monthId,id,result);
	}

	/**
	 * 点击情景里的题目
	 */
	var onDoSceneQuest = function(){
		$(this).addClass("active").siblings().removeClass("active");
		var sceneResult = $(this).attr("data-result");
		var sceneMonthId = $(this).parents("li.item").attr("data-monthId");
		var sceneId = $(this).parents("li.item").attr("data-id");
		var index = $(this).parents("li.item").attr("data-index");
		var questId = $("#dstDetailQuest .quest-resut").attr("data-id");
		if( questId == sceneId ){
			var className = sceneResult == "1" ? "quest-pass" : sceneResult == "0" ? "quest-fail" : "";
			$("#dstDetailQuest .quest-resut ." + className).addClass("active").siblings().removeClass("active");
		}
		presentSave(sceneMonthId,sceneId,sceneResult,index);
		$("#dstDetailScene .scene-btn").addClass("active");
	}

	/**
	 * 下一步
	 */
	var nextStep = function(questions,monthId,id,resultArr){
		var topMonthId = $("#topicTop").attr("data-monthId");
		var bottomMonthId = $("#topicBottom").attr("data-monthId");
		if( !bottomMonthId ){
			var locationObj = $servers.getNextQuest(questions,resultArr,topMonthId,monthId,id);
			if( locationObj.extremeTop ){ // 找到0月还没找到顶点的情况
				var questFirst = questions[0];
				$("#topicTop").html(questFirst.month).attr("data-monthId",questFirst.id);
				tipMsgModal(locationObj);
			}else if( locationObj.extremeBottom ){
				var questLast = questions[questions.length-1];
				$("#topicBottom").html(questLast.month).attr("data-monthId",questLast.id);
				endMsgModal(questions);
			}else{
				$("#tabShow ul li").eq(locationObj.monthIndex).find("span").eq(locationObj.questIndex).click();
			}
		}else{
			endMsgModal(questions);
		}
	}

	/**
	 * 做题
	 */
	var onDoQuest = function(){
		var This = $(this);
		This.addClass("active").siblings().removeClass("active");
		var monthId = This.parent().attr("data-monthId");
		var month = This.parent().attr("data-month");
		var id = This.parent().attr("data-id");
		var index = This.parent().attr("data-index");
		var data = This.data();
		var topMonthId = $("#topicTop").attr("data-monthId");
		var bottomMonthId = $("#topicBottom").attr("data-monthId");
		setTimeout(function(){
			carouselInit(monthId-1);
			presentSave(monthId,id,data.result,index);
			// 找顶部
			if( !topMonthId && resultArr.length >= 2 ){
				var flag1 = $servers.getMonthResult(data.questions,resultArr,resultArr.length-1,"1");
				var flag2 = $servers.getMonthResult(data.questions,resultArr,resultArr.length-2,"1");
				if( flag1 && flag2 ){
					$("#topicTop").html( month ).attr("data-monthId",monthId);
				}
			}
			// 找底部
			if( topMonthId && !bottomMonthId && resultArr.length >= 2 ){
				var flag3 = $servers.getMonthResult(data.questions,resultArr,resultArr.length-1,"0");
				var flag4 = $servers.getMonthResult(data.questions,resultArr,resultArr.length-2,"0");
				if( flag3 && flag4 ){
					$("#topicBottom").html( month ).attr("data-monthId",monthId);
					endMsgModal(data.questions);
				}else{
					$("#topicBottom").html("不确定").removeAttr("data-monthId");
				}
			}
			topMonthId = $("#topicTop").attr("data-monthId");
			bottomMonthId = $("#topicBottom").attr("data-monthId");
			// 情景
			var sceneLen = $("#dstDetailScene .scene-con .item-wrap .item").length;
			// 确定下一个问题id和monthId
			if( sceneLen <= 0 ){
				nextStep(data.questions,monthId,id,resultArr);
			}else{
				$("#dstDetailScene .scene-con .item-wrap .item").each(function(i){
					var sceneId = $(this).attr("data-id");
					if( sceneId == id ){
						var sceneIndex = data.result == "1" ? 0 : data.result == "0" ? 1 : null;
						if( sceneIndex != null ){
							$("#dstDetailScene li.item .item-result > div").unbind("click");
							$("#dstDetailScene li.item .item-result > div").click(onDoSceneQuest);
							$(this).find(".item-result > div").eq(sceneIndex).click();
						}
					}
				});
				sceneJump(data.questions,monthId,id,resultArr);
			}
		},500);
	}

	/**
	 * 情景相关
	 */
	var sceneJump = function(questions,monthId,id,resultArr){
		var sceneLenActive = $("#dstDetailScene li.item .item-result > div.active").length;
		if( sceneLenActive > 0 ){
			$("#dstDetailScene .scene-btn").addClass("active");
			if( !status ) {
				// 做情景题目
				$("#dstDetailScene li.item .item-result > div").unbind("click");
				$("#dstDetailScene li.item .item-result > div").click(onDoSceneQuest);
				$("#dstDetailScene .scene-btn").unbind("click");
				$("#dstDetailScene .scene-btn").click(function(){
					nextStep(questions,monthId,id,resultArr);
				});
			}
		}
	}

	/**
	 * 选择题目
	 */
	var onQuestSelect = function(){
		// 月、题目选中样式
		$(this).parents("ul").find("li .tab-month").removeClass("active");
		$(this).parents("ul").find("li .tab-quest-box span").removeClass("active");
		$(this).addClass("active");
		$(this).parents("li").children(".tab-month").addClass("active");
		// 
		var data = $("#dstDetailType > div.item.active").data();
		var questions = $servers.handleQuestions(data.questions);
		var monthId = $(this).parents("li").children(".tab-month").attr("data-monthId");
		var id = $(this).attr("data-id");
		var answer = $(this).attr("data-answer");
		var quest = $servers.getQuest(questions,monthId,id,answer);
		var questGroup = $servers.getQuestGroup(questions,quest,resultArr);
		$ui.quest({
			"id":"dstDetailQuest",
			"data":quest,
		});
		if( $("#dstDetailQuest .quest-con > div").height() > 78 ){
			$("#dstDetailQuest .quest-con").css({"align-items":"flex-start"});
		};
		$ui.scene({
			"id":"dstDetailScene",
			"group":quest.group,
			"list":questGroup,
		});
		sceneJump(questions,monthId,id,resultArr);
		if( !status ) {
			// 做题目
			$("#dstDetailQuest .quest-resut > div").unbind("click");
			$("#dstDetailQuest .quest-resut > div").data({"questions":questions,"type":data.type});
			$("#dstDetailQuest .quest-resut > div").click(onDoQuest);
		}
	}

	/**
	 * 选择月龄
	 */
	var onMonthSelect = function(){
		$(this).next().find("span").eq(0).click();
	}

	/**
	 * 轮播初始化
	 */
	var carouselInit = function(i){
		if( w_li*i < w_diff ){
			if( i == 0 ){
				$("#tabShow .tab-box").stop().animate({"marginLeft":'0px'});
			}else if( i > 0 ) {
				$("#tabShow .tab-box").stop().animate({"marginLeft":(-w_li*(i-1))+'px'});
			}
		}else{
			$("#tabShow .tab-box").stop().animate({"marginLeft":(-w_diff)+'px'});
		}
	}
	
	/**
	 * 月龄定位
	 */
	event.init = function(i,_diff,_li,params,answer){
		w_diff = _diff;
		w_li = _li;
		status = params.status;
		carouselInit(i);
		resultArr = answer ? answer : [];
		// 选择月龄
		$("#tabShow ul li > .tab-month").unbind("click");
		$("#tabShow ul li > .tab-month").data("status",status);
		$("#tabShow ul li > .tab-month").click(onMonthSelect);
		// 选择题目
		$("#tabShow ul li > .tab-quest-box > span").unbind("click");
		$("#tabShow ul li > .tab-quest-box > span").click(onQuestSelect);
		// 初始化
		$("#tabShow ul li").eq(i).children(".tab-month").click();
	}

	/**
	 * 轮播
	 */
	event.carousel = function(i,_diff,_li){
		w_diff = _diff;
		w_li = _li;
		// 点击左右箭头
		$("#arrowRight").unbind("click");
		$("#arrowRight").click(function(){
			if( (w_li*(i+1)) < w_diff ){
				i++;
				$("#tabShow .tab-box").animate({"marginLeft":(-w_li*i)+'px'});
			}else{
				$("#tabShow .tab-box").animate({"marginLeft":(-w_diff)+'px'});
			}
		});
		$("#arrowLeft").unbind("click");
		$("#arrowLeft").click(function(){
			if( (w_li*(i-1)) > w_diff ){
				i = parseInt( w_diff/w_li )-1;
				$("#tabShow .tab-box").animate({"marginLeft":(-w_diff+w_li)+'px'});
			}else if( i-1 > 0 ){
				i--;
				$("#tabShow .tab-box").animate({"marginLeft":(-w_li*i)+'px'});
			}else{
				i = 0;
				$("#tabShow .tab-box").animate({"marginLeft":'0px'});
			}
		});
	}

	/**
	 * 查看患者基本信息
	 */
	event.onInfoClick = function(){
		var info = $(this).data("info");
		var className = "dstModal";
		$bb.modal({
			"id":"dstDetail",
			"className":className,
			"tit":"基本情况",
			"size":"modal-lg"
		},function(){
			$ui.info({
				"dom":$("." + className + " .modal-body"),
				"flag":true,
				"info":info,
			});
			$("." + className).modal("show");
		});
	}

	return event;
})